package com.executor;

import java.util.concurrent.ForkJoinPool;
import java.util.concurrent.RecursiveTask;
/**
 *
 * 功能描述: 
 *
 * @param: 通过fork/join 进行求合计算
 * @return: 
 * @auther: csh
 * @date: 2023/4/17 9:52 下午
 */
public class ArraySum extends RecursiveTask<Long> {
    
    private static final int THRESHOLD = 1000;   // 阈值，当数组大小小于该值时不再进行拆分
    private long[] arr;
    private int start;
    private int end;
    
    public ArraySum(long[] arr, int start, int end) {
        this.arr = arr;
        this.start = start;
        this.end = end;
    }

    @Override
    protected Long compute() {
        if (end - start <= THRESHOLD) {  // 如果数组大小小于阈值，直接计算
            long sum = 0L;
            for (int i = start; i < end; i++) {
                sum += arr[i];
            }
            return sum;
        } else {   // 如果数组大小大于阈值，拆分为两个任务并执行
            int mid = (start + end) / 2;
            ArraySum left = new ArraySum(arr, start, mid);
            ArraySum right = new ArraySum(arr, mid, end);
            left.fork();
            right.fork();
            return left.join() + right.join();
        }
    }

    public static void main(String[] args) {
        int N = 100000;
        long[] arr = new long[N];
        for (int i = 0; i < N; i++) {
            arr[i] = i;
        }
        ForkJoinPool pool = new ForkJoinPool();
        long sum = pool.invoke(new ArraySum(arr, 0, arr.length));
        System.out.println("累加起来的结果是: " + sum);
    }
}
